package net.lulihu.common_util.jdbc.mapper;


import net.lulihu.Assert;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 数据库映射使用对象
 */
public class Dao {

    private Dao() {
    }

    /**
     * NoTypeDaoMapper缓存
     * <p>
     * 因为本身NoTypeDaoMapper为线程安全对象所以使用缓存减少对象创建
     */
    private static final NoTypeDaoMapper noTypeDaoMapper;

    /**
     * SpecifiedTypeMapper缓存
     * <p>
     * key->返回值类型，value->SpecifiedTypeMapper
     */
    private static final Map<Class<?>, SpecifiedTypeMapper<?>> specifiedTypeMapper;

    static {
        noTypeDaoMapper = new NoTypeDaoMapper();
        specifiedTypeMapper = new ConcurrentHashMap<>();
    }

    /**
     * 获取无需指定类型的数据库映射对象
     * <p>
     * 使用默认数据源
     *
     * @return NoTypeDaoMapper
     */
    public static NoTypeDaoMapper mapper() {
        return noTypeDaoMapper;
    }

    /**
     * 获取指定数据库映射对象
     *
     * @param resultClass 返回值类型
     * @return SpecifiedTypeMapper
     */
    @SuppressWarnings("unchecked")
    public static <T> SpecifiedTypeMapper<T> mapper(Class<T> resultClass) {
        Assert.notNull(resultClass, "未定义返回值类型....");
        return (SpecifiedTypeMapper<T>) specifiedTypeMapper.computeIfAbsent(resultClass, SpecifiedTypeMapper::new);
    }

}
